//Given an integer n, return all the numbers in the range [1, n] sorted in lexic
//ographical order. 
//
// 
// Example 1: 
// Input: n = 13
//Output: [1,10,11,12,13,2,3,4,5,6,7,8,9]
// Example 2: 
// Input: n = 2
//Output: [1,2]
// 
// 
// Constraints: 
//
// 
// 1 <= n <= 5 * 104 
// 
//
// 
// Follow up: Could you optimize your solution to use O(n) runtime and O(1) spac
//e? 
// 👍 174 👎 0


package leetcode.editor.cn;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

//Java：Lexicographical Numbers
class P386LexicographicalNumbers {
    public static void main(String[] args) {
        Solution solution = new P386LexicographicalNumbers().new Solution();
        // TO TEST
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public List<Integer> lexicalOrderSort(int n) {
            List<Integer> result = new ArrayList<>(n);
            for (int i = 1; i <= n; i++) {
                result.add(i);
            }
            Collections.sort(result, Comparator.comparing(Object::toString));
            return result;
        }

        public List<Integer> lexicalOrderDfs(int n) {
            List<Integer> list = new ArrayList<>();
            for (int i = 1; i < 10; i++){
                dfs(n, i, list);
            }
            return list;
        }
        private void dfs(int n,int i,List<Integer>list){
            if(i>n){
                return ;
            }
            list.add(i);
            for(int j=0;j<=9;j++){
                dfs(n,i*10+j,list);
            }
        }

         public List<Integer> lexicalOrder(int n) {
             List<Integer> list = new ArrayList<>();
             int curr = 1;
             //10叉树的先序遍历
             for(int i=0;i<n;i++){
                 list.add(curr);
                 if(curr*10<=n){
                     curr*=10;//进入下一层
                 }else{
                     if(curr>=n) {
                         curr/=10;//如果这一层结束了
                     }
                     curr+=1;
                     while(curr%10==0) {
                         curr/=10;//如果>10就要返回上一层
                     }
                 }
             }
             return list;
         }

    }


//leetcode submit region end(Prohibit modification and deletion)

}